
import { Component, OnInit, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import { Http, Response } from '@angular/http';
import { DxDataGridComponent } from 'devextreme-angular';
import 'rxjs/add/operator/map';
import { Subject } from 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
declare const $: any;
import * as Enumerable from 'linq';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDropDownBoxComponent } from 'devextreme-angular';
import { QueryModel } from '../../model/report/query-model';
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { DxTreeViewModule, DxListModule, DxTemplateModule } from 'devextreme-angular';
import { UserModel } from '../../model/sys/user-model';
import { UserModule } from './user.module';
import { Notifycation } from 'app/ptpmc/comm/notifycation';
import { DateUtils } from '../../model/comm/date-utils';
import { SubArea } from '../../model/report/sub-area';
export class User {
    uid: string;
    uname: string;
    mail: string;
    password: string;
    createBy: string;
    updateBy: string;
}
export class AllsubArea {
    subArea: string;
    userId: string;
}
@Component({
    selector: 'app-report-user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.scss']
})

export class UserComponent implements OnInit {
    public subAreaItems: SubArea[];
    public subAareSelected: any;
    title = '系统用户管理';
    public userList: any[] = [];
    public subAreaList: any[] = [];
    public roleList: any[] = [];
    curUserRoleList: any[] = [];
    dialogTitle = '用户角色管理';
    dialogAreaTitle = '区域管理';
    curUserDetail: any;
    popupVisible = false;
    addUserDialogVisible = false;
    addUserAreaDialogVisible = false;
    selectedItems: any[] = [];
    userModel: User = {
        uid: '',
        uname: '',
        mail: '',
        password: '',
        createBy: UserModel.userId,
        updateBy: UserModel.userId
    };

    constructor(private commService: CommService) {
    }

    ngOnInit() {
        this.curUserRoleList = UserModel.roles;
        this.getReportData();
        //this.getReportSubAreaData();
        this.subAreaItems = this.commService.getSubAreas();
        // this.subAareSelected = this.subAreaItems;
        // debugger
    }

    /**
     * 获取表格数据
     */
    getReportData(): void {
        this.commService
            .getList({}, ReportUrls.AllUser)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.userList = model.data.allUser;
                    this.roleList = model.data.allRole;
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }

            });
    }
    getReportSubAreaData(userDetail: any): void {
        this.clearEquipmentSelected();
        this.curUserDetail = userDetail.data;
        this.addUserAreaDialogVisible = true;
        this.commService
            .doGet(`${ReportUrls.AllSubArea}/${this.curUserDetail.id}`)
            .subscribe(model => {
                if (model.resultCode === 200 && model.data) {
                    const areas = model.data[0].subArea;
                    var str = areas.split(',')
                    str.forEach(element => {
                        var data= this.subAreaItems.find(item=>item.subArea===element);
                        if(data){
                            this.subAareSelected.push(data);
                        }
                    });
                } 
               
            });
            
    }
    

    @ViewChild("dddb") dddb: DxDropDownBoxComponent;
    clearEquipmentSelected() {
        this.subAareSelected = [];
    }
    equipmentSelectedOk() {
        this.dddb.instance.close();
    }
    roleIsChecked(role: any) {
        const a = this.curUserRoleList.find(e => e.roleId === role.id);
        return a !== undefined;
    }

    bindRoleToUser(role: any) {
        this.commService.doGet(ReportUrls.roles + '/' + this.curUserDetail.id + '/' + role.id).subscribe(model => {
            Notifycation.showNotification(model.resultCode === 200 ? '更新成功' : '更新失败', 'info');
        });
    }

    showDetail(userDetail: any) {
        this.curUserDetail = userDetail.data;
        this.commService.doGet(ReportUrls.roles + '/' + this.curUserDetail.id).subscribe(model => {
            if (model.resultCode === 200) {
                this.curUserRoleList = model.data;
                this.popupVisible = true;
            }
        });
        debugger
    }

    selectionChanged(data) {
        this.selectedItems = data.selectedRowsData;
    }

    updateUsers() {
        if (this.selectedItems.length <= 0) {
            alert('请先选中要修改的用户');
            return;
        }
        debugger
        const arr = new Array<User>();
        this.selectedItems.forEach(e => {
            arr.push({
                uid: e.id,
                uname: e.name,
                mail: e.email,
                password: e.password,
                createBy: UserModel.userId,
                updateBy: UserModel.userId
            });
        });
        this.commService
            .getList(arr, ReportUrls.updateUser)
            .subscribe(model => {
                Notifycation.showNotification(model.resultCode === 200 ? '修改成功' : '修改失败', 'info');
                this.getReportData();
                this.addUserDialogVisible = false;
            });
    }
    updateSubArea() {
        const updateModel: any = new AllsubArea();
        updateModel.subArea = this.subAareSelected.map(item=>item.subArea).join(',');
        updateModel.userId =  this.curUserDetail.id;
        this.commService
            .update(updateModel, ReportUrls.UpdateAllSubArea)
            .subscribe(model => {
                Notifycation.showNotification(model.resultCode === 200 ? '修改成功' : '修改失败', 'info');
                this.addUserDialogVisible = false;
            });
    }

    delUser() {
        if (this.selectedItems.length <= 0) {
            alert('请先选中要删除的用户');
            return;
        }
        if (confirm('是否确认删除选择的用户？')) {
            this.commService
                .getList(this.selectedItems, ReportUrls.DelUser)
                .subscribe(model => {
                    if (model.resultCode === 200) {
                        this.getReportData();
                        this.selectedItems = [];
                    }
                    Notifycation.showNotification(model.resultCode === 200 ? '删除成功' : '删除失败', 'info');
                });
        }

    }

    registerUser() {
        if (this.userModel.uid === '' || this.userModel.password === '') {
            alert('请填写正确的表单');
            return;
        }
        this.commService
            .getList(this.userModel, ReportUrls.register)
            .subscribe(model => {
                Notifycation.showNotification(model.resultCode === 200 ? '注册成功' : '注册失败', 'info');
                this.getReportData();
                this.addUserDialogVisible = false;
            });
    }

}
